﻿using System;
using System.Collections.Generic;
using DevelopTool.Bll.SchedulerBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model.SchedulerModels;
using Sunny.UI;

namespace DevelopTool.Forms.SchedulerForms
{
    public partial class SchedulerForm_Sql : BaseUIPage
    {
        /// <summary>
        /// 定时任务对象
        /// </summary>
        private Scheduler scheduler;

        /// <summary>
        /// 定时任务sql对象
        /// </summary>
        private Scheduler_Sql scheduler_Sql;


        private Scheduler_SqlBll scheduler_SqlBll;


        public SchedulerForm_Sql(Scheduler scheduler)
        {
            InitializeComponent();

            this.scheduler = scheduler;
        }


        private void SchedulerForm_Sql_Load(object sender, EventArgs e)
        {
            this.scheduler_SqlBll = new Scheduler_SqlBll();

            //加载内容类型下拉框数据
            List<dynamic> sqlTypeList = new List<dynamic>() {
                new{ Text="Sql语句",Value=1},
                new{ Text="存储过程",Value=2},
            };
            this.cboSqlType.ValueMember = "Value";
            this.cboSqlType.DisplayMember = "Text";
            this.cboSqlType.DataSource = sqlTypeList;


            this.scheduler_Sql = scheduler_SqlBll.GetBySchedulerId(scheduler.Id);
            if (this.scheduler_Sql == null)
            {
                //如果没有的话，就创建一个
                this.scheduler_Sql = scheduler_SqlBll.Save(new Scheduler_Sql() { SchedulerId = this.scheduler.Id });
            }

            if (this.scheduler_Sql.ExecuteType > 0)
            {
                this.cboSqlType.SelectedValue = this.scheduler_Sql.ExecuteType;
            }


            if (this.scheduler_Sql.DbInfo != null && this.scheduler_Sql.DbInfo.Id > 0)
            {
                this.dbinfoComboBox.DefaultSelectedDbInfo = this.scheduler_Sql.DbInfo;
            }

            this.codeEditorControl.ContentText = this.scheduler_Sql.Sql;

        }


        /// <summary>
        /// 保存，在父窗口中调用
        /// </summary>
        public override bool Call()
        {            
            if (this.dbinfoComboBox.SelectedDbInfo == null)
            {
                this.ShowWarningNotifier("请选择数据库连接");
                return false;
            }
            if (string.IsNullOrEmpty(this.codeEditorControl.ContentText))
            {
                this.ShowWarningNotifier("请输入需要执行的sql");
                return false;
            }

            this.scheduler_Sql.ExecuteType = this.cboSqlType.SelectedValue.ToInt();
            this.scheduler_Sql.Sql = this.codeEditorControl.ContentText;
            this.scheduler_Sql.DbInfo = this.dbinfoComboBox.SelectedDbInfo;

            this.scheduler_Sql = scheduler_SqlBll.Save(this.scheduler_Sql);

            return true;
        }

    }
}
